package com.cfwx.datastructure.sort;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * 使用Collection.sort对List元素进行排序
 * 使用Arrays.sort对数组元素进行排序
 * @category
 */
public class UseCollections {
	public static void main(String arg[]){
		String[] array = new String[] { "hello", "wang", "awt"};
		Arrays.sort(array);

		StringBuilder digestBuilder = new StringBuilder();
		for (String item : array) {
			digestBuilder.append(item+" ");
		}
		System.out.println(digestBuilder.toString());


		List<String> list = new ArrayList<String>();
		list.add("hello");
		list.add("wang");
		list.add("awt");
		list.add("112");
		Collections.sort(list);
		for(String s:list){
			System.out.print(s+" ");
		}
		System.out.println();
		
		
		
		List<Apple> appleList = new ArrayList<Apple> ();
		appleList.add(new Apple(34,"apple1"));
		appleList.add(new Apple(1,"apple2"));
		appleList.add(new Apple(12,"apple3"));
		appleList.add(new Apple(65,"apple4"));
		appleList.add(new Apple(54,"apple5"));
		appleList.add(new Apple(4,"apple6"));
		appleList.add(new Apple(4,"apple7"));
		Collections.sort(appleList, new MyComparator());
		for(Apple eApple:appleList){
			System.out.println(eApple.toString()+" ");
		}
	}

	static class MyComparator implements Comparator<Apple>{
		/**
		 * 重写Comparator的compare方法，比较用来排序的两个参数。
		 * 根据第一个参数小于、等于或大于第二个参数分别返回负整数、零或正整数。
		 */
		@Override
		public int compare(Apple a1, Apple a2) {
			if(a1.weight>a2.weight) {
				return 1;
			}else if(a1.weight==a2.weight) 
			{
				return 0;
			}else{
				return -1;
			}

		};

	}

	static class Apple {
		int weight;
		String name;
		Apple (int weight,String name){
			this.weight = weight;
			this.name = name;
		}
		public String toString(){

			return name+"重量为："+weight;
		}
	}

}


